package net.opentsdb.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * @author Hujf
 * @title: PluginLoader
 * @date 2021-09-13 9:46
 * @description: 插件加载器
 */
public class PluginLoader {
    private static final Logger LOG = LoggerFactory.getLogger(PluginLoader.class);

    public static void loadJARs(String plugin_path) {
        File file = new File(plugin_path);
        if (!file.isDirectory()) {
            throw new IllegalArgumentException(
                    "The path specified was not a directory");
        }

        ArrayList<File> jars = new ArrayList<>();
        searchForJars(file, jars);

    }

    private static void searchForJars(File file, ArrayList<File> jars) {
    }

    public static <T> T loadSpecificPlugin(final String name, final Class<T> type) {
        if (name.isEmpty()) {
            throw new IllegalArgumentException("Missing plugin name");
        }
        ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
        Iterator<T> it = serviceLoader.iterator();
        if (!it.hasNext()) {
            LOG.warn("Unable to locate any plugins of the type: " + type.getName());
            return null;
        }

        while(it.hasNext()) {
            T plugin = it.next();
            if (plugin.getClass().getName().equals(name) || plugin.getClass().getSuperclass().getName().equals(name)) {
                return plugin;
            }
        }

        LOG.warn("Unable to locate plugin: " + name);
        return null;
    }
}
